//
//  ViewController.m
//  PushToTalk
//
//  Created by apple on 14-5-18.
//  Copyright (c) 2014年 GJYSK. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize SpinnerIndicatorView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    toggle = YES;
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    [audioSession setActive:YES error:&error];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) connection:(NSURLConnection *)connection
   didFailWithError:(NSError *)error{
    NSLog(@"An error happened");
    NSLog(@"%@", error);
}

- (void) connection:(NSURLConnection *)connection
     didReceiveData:(NSData *)data
{
    [self.connectionData appendData:data];
    NSLog(@"Received data. length : %d", [self.connectionData length]);
    NSString *statusText = [[NSString alloc] initWithFormat:@"%d", [self.connectionData length]];
}

- (void) connectionDidFinishLoading
:(NSURLConnection *)connection{
    /* 下载的数据 */
    
    NSLog(@"下载成功");
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    
    
    //  NSString* paths = [NSHomeDirectory()
    //  stringByAppendingPathComponent:@""];
    NSString *fileName = [[NSString alloc] initWithFormat:@"%@/%@",cachesDir, @"TestAudio.mp3"];
    NSLog(@"%@",fileName);
    
    if ([self.connectionData writeToFile:fileName atomically:YES]) {
        NSLog(@"保存成功.");
        
        NSLog(@"开始播放音乐.");
        
        // Play music.
        NSString *currentSoundFilePath = fileName;
        NSURL *currentFileURL = [NSURL fileURLWithPath:currentSoundFilePath];
        self.AudioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:currentFileURL error:nil] autorelease];
        self.AudioPlayer.numberOfLoops = 0;//播放次数 0为1次 1为两次
        self.AudioPlayer.volume = 0.3;//播放音量
        
        [self.AudioPlayer play];//播放音乐
    }
    else
    {
        NSLog(@"保存失败.");
    }
    
    /* do something with the data here */
}

- (void) connection:(NSURLConnection *)connection
 didReceiveResponse:(NSURLResponse *)response{
    [self.connectionData setLength:0];
}

- (void) viewDidUnload{
    [super viewDidUnload];
    [self.connection cancel];
    self.connection = nil;
    self.connectionData = nil;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"finish");//设置代理的AVAudioPlayer对象每次播放结束都会触发这个函数
}

- (IBAction)PushToTalk:(id)sender
{
    // 采集声音。
    if (!toggle) {
        toggle = YES;
        [SpinnerIndicatorView stopAnimating];
        
        NSLog(@"Using File called: %@",RecordedTempFileName);
        //Stop the recorder.
        [Recorder stop];
    }
    
    
    toggle = NO;
    [SpinnerIndicatorView startAnimating];
    
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKeyPath:AVFormatIDKey];
    
    [recordSetting setValue:[NSNumber numberWithFloat:[FreqTextField.text floatValue]] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: [ValueField.text intValue]] forKey:AVNumberOfChannelsKey];
    
    RecordedTempFileName = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];
    NSLog(@"Using File called: %@",RecordedTempFileName);
    //Setup the recorder to use this file and record to it.
    Recorder = [[ AVAudioRecorder alloc] initWithURL:RecordedTempFileName settings:recordSetting error:&error];
    //Use the recorder to start the recording.
    //Im not sure why we set the delegate to self yet.
    //Found this in antother example, but Im fuzzy on this still.
    [Recorder setDelegate:self];
    //We call this to start the recording process and initialize
    //the subsstems so that when we actually say "record" it starts right away.
    [Recorder prepareToRecord];
    //Start the actual Recording
    [Recorder record];
    //There is an optional method for doing the recording for a limited time see
    //[recorder recordForDuration:(NSTimeInterval) 10]
    
    [self performSelector:@selector(Play) withObject:nil afterDelay:3.0f];
}

- (void) Play
{
    // 模拟从服务器读取声音文件。
    NSLog(@"Download file ...");
    NSString *urlAsString = @"http://download.coolfay.com/audio/TestAudio.mp3";
    NSURL *url = [NSURL URLWithString:urlAsString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableData *data = [[NSMutableData alloc] init];
    
    self.connectionData = data;
    [data release];
    NSURLConnection *newConnection = [[NSURLConnection alloc]
                                      initWithRequest:request
                                      delegate:self
                                      startImmediately:YES];
    self.connection = newConnection;
    [newConnection release];
    if (self.connection != nil){
        NSLog(@"Successfully created the connection");
    } else {
        NSLog(@"Could not create the connection");
    }
}

@end









